<?php

namespace app\api\controller;

use think\facade\Db;

class User
{
     //单点登录
     public function single_signon(){
        $param = input();
        if (empty($param['userId'])) {
            $result = [
                "code"=>-1,
                "msg"=>"用户id不能为空",
                "data"=>""
            ];
            return json($result);
        }
        if (empty($param['token'])) {
            $result = [
                "code"=>-1,
                "msg"=>"token不能为空",
                "data"=>""
            ];
            return json($result);
        }
        //根据userid查询用户是否存在
        $flag_user = $this->flag_usereqw($param['userId']);
        if(empty($flag_user)){
            $result = [
                "code"=>-1,
                "msg"=>"用户不存在",
                "data"=>""
            ];
            return json($result);
        }

        //验证toekn是否正确  LyZFDcHF2g8   token = YYYY-MM-DD+用户ID+ Secrect值，通过MD5加密，实现认证
        $time = date("Y-m-d",time());
        $token = md5($time.$param['userId']."LyZFDcHF2g8");
        if($param['token'] != $token){
            $result = [
                "code"=>-1,
                "msg"=>"token验证错误,请重新输入",
                "data"=>""
            ];
            return json($result);
        }
        //dump($token);die;
        //重定向
        return redirect('https://xdblq20221109.my.fxiaoke.com/oauth/sp/callback/xddlse?code='.$param['userId']);

    }

    //CRM同步待办->门户
    public function sync_todo(){
       $param = input();
        //获取待办数据
        $data = $this->message_todo($param["currentOpenUserId"]);
        //dump($data);die;
        // $data = [
        //    [
        //         "syscode"=>"XBCRM",
        //         "flowid"=>"001",
        //         "requestname"=>"测试流程001",
        //         "workflowname"=>"测试流程名称001",
        //         "nodename"=>"测试节点001",
        //         "pcurl"=>"http://www.baidu.com",
        //         "appurl"=>"http://mobile.baidu.com",
        //         "creator"=>"qwe",
        //         "createdatetime"=>"2018-12-04 17:56:00",
        //         "receiver"=>"qwe",
        //         "receivedatetime"=>"2018-12-04 17:56:00",
        //         "isremark"=>"0",
        //         "viewtype"=>"1",
        //         "receivets"=>"1602817491990"
        //    ]
        // ];
        //处理数据
        foreach($data as $k=>$v){
            $v["new_pcurl"] = "http://jd.yquewx.cn/api/user/todo_address_verification?flowid=".$v["flowid"]."&type=1";//http://117.35.117.68:9991
            $v["new_appurl"] = "http://jd.yquewx.cn/api/user/todo_address_verification?flowid=".$v["flowid"]."&type=2";
            $v["addtime"] = time();
            $data[$k] =$v;
        }
       
        Db::name("message_todo")->insertAll($data);
        //同步待办数据到门户
        foreach($data as $key=>$val){
           $neqdata = [
                "syscode"=>$val["syscode"],
                "flowid"=>$val["flowid"],
                "requestname"=>$val["requestname"],
                "workflowname"=>$val["workflowname"],
                "nodename"=>$val["nodename"],
                "pcurl"=>$val["new_pcurl"],
                "appurl"=>$val["new_appurl"],
                "creator"=>$val["creator"],
                "createdatetime"=>$val["createdatetime"],
                "receiver"=>$val["receiver"],
                "receivedatetime"=>$val["receivedatetime"],
                "isremark"=>$val["isremark"],
                "viewtype"=>$val["viewtype"],
                "receivets"=>$val["receivets"]
           ];
           $url = 'http://10.108.0.182:18081/rest/ofs/ReceiveRequestInfoByJson';
           
           $res =  json_encode($neqdata,JSON_UNESCAPED_UNICODE);
          // dump($res);die;
           $method = 'POST';
           $header = [
                'Content-Type:application/json',
                'accept:*/*',
                'connection:Keep-Alive'
            ];
           $dsdf = $this->http_curl($url,$method, $res, $header, $timeout = 10);
           if($dsdf['operResult'] == '1'){
                Db::name("message_todo")->where("flowid",$val["flowid"])->update(["status"=>2]);
           }else{
                Db::name("message_todo")->where("flowid",$val["flowid"])->update(["status"=>3]);
           }
        }
        
        return 1;


    }
    //待办地址验证
    public function todo_address_verification(){
        $param = input();
        if(empty($param["type"])){
            $result = [
                "code"=>-1,
                "msg"=>"参数错误",
                "data"=>""
            ];
            return json($result);
        }
        if(empty($param["flowid"])){
            $result = [
                "code"=>-1,
                "msg"=>"参数不正确",
                "data"=>""
            ];
            return json($result);
        }
        if (empty($param['userId'])) {
            $result = [
                "code"=>-1,
                "msg"=>"用户id不能为空",
                "data"=>""
            ];
            return json($result);
        }
        if (empty($param['token'])) {
            $result = [
                "code"=>-1,
                "msg"=>"token不能为空",
                "data"=>""
            ];
            return json($result);
        }
        
        //根据userid查询用户是否存在
        $flag_user = $this->flag_usereqw($param['userId']);
      
        if(empty($flag_user)){
            $result = [
                "code"=>-1,
                "msg"=>"用户不存在",
                "data"=>""
            ];
            return json($result);
        }
        //获取免登录地址
        $loginUrl = $this->login_free_address($flag_user);
        //验证toekn是否正确  LyZFDcHF2g8   token = YYYY-MM-DD+用户ID+ Secrect值，通过MD5加密，实现认证
        $time = date("Y-m-d",time());
        $token = md5($time.$param['userId']."LyZFDcHF2g8");
        if($param['token'] != $token){
            $result = [
                "code"=>-1,
                "msg"=>"token验证错误,请重新输入",
                "data"=>""
            ];
            return json($result);
        }
        //type 1pc地址  2app地址
        $message_todo = Db::name("message_todo")->where("flowid",$param["flowid"])->find();
        if($param["type"] == 1){
            $newUrl = $message_todo["pcurl"];
        }elseif($param["type"] == 2){
            $newUrl = $message_todo["appurl"];
        }else{
            $result = [
                "code"=>-1,
                "msg"=>"类型不存在",
                "data"=>""
            ];
            return json($result);
        }
        $newUrl = $loginUrl.'&source='.urlencode($newUrl);
        //dump($newUrl);die;
        //重定向
        return redirect($newUrl);
    }

    //获取单点免登录地址
    public function login_free_address($userid){
          $orderSn = $this->GetRandStr();
        
          $qwe = $this->corpAccessToken();
          $url ='https://open.fxiaoke.com/cgi/sso/loginurl/get';  //查询免登录地址
          $corpAccessToken = $qwe['corpAccessToken'];   
          $corpId = $qwe['corpId'];
          $timestamp = substr(microtime(date("Y-m-d H:i:s",time()))*1000,0,13);
         // $timestamp = time()."000";
          $nonce = $orderSn;//16位随机字符串（字符取值范围数字、大小写字母），请保证至少1分钟内请求中随机串不重复，用来防重放
          $type = 3;
          $account = $userid;//代表纷享销客侧唯一员工的账号值
          $sing_str = [$corpAccessToken,$corpId,$timestamp,$nonce,$account,$type,"69a6c56e23234bc9b56992f1468d103a"];
          sort($sing_str,SORT_STRING);
          $sing_str = implode($sing_str);
          $signature = sha1($sing_str);
        //   1.首先将corpAccessToken、corpId、timestamp、nonce、account、type字段值以及appSecret（自建应用-开发者模式中可以查看）按
        //     照字符串值进行自然序排序。
        //   2.将排序后的字符串进行拼接。
        //   3.将拼接后的字符串进行SHA1计算进行16进制编码后获取签名。
          $res =  json_encode(compact('corpAccessToken', 'corpId', 'timestamp','nonce','type','account','signature'),JSON_UNESCAPED_UNICODE);
         // dump($res);die;
          $method = 'POST';
          $header = [
                         'Content-Type:application/json'
                     ];
          $dsdf = $this->http_curl($url,$method, $res, $header, $timeout = 10);
          if(!empty($dsdf) && isset($dsdf) && $dsdf['errorCode'] == '0' && $dsdf['errorMessage'] == 'success')
           {
               if(empty($dsdf["loginUrl"])){
                  return "";
               }else{
                  return $dsdf["loginUrl"];
               }
           }else{
              return ""; 
           }
    }
 
  

    //生成16位随机字符串
    function GetRandStr($len=16)
    {
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        );
        $charsLen = count($chars) - 1;
        shuffle($chars);
        $output = "";
        for ($i=0; $i<$len; $i++){
            $output .= $chars[mt_rand(0, $charsLen)];
        }
        return $output;
    }

    /**
     * 处理CRM已办->门户
    */
    public function crm_processing_done(){
        $param = input();
        if(empty($param["currentOpenUserId"])){
            $result = [
                "code"=>-1,
                "msg"=>"参数不正确",
                "data"=>""
            ];
            return json($result);
        }
        //获取已办数据
        $data = $this->message_handled($param["currentOpenUserId"]);
        foreach($data as $k=>$v){
            $v["add_time"] = time();
            $data[$k] =$v;
        }
        Db::name("processing_done")->insertAll($data);
        //同步已处理已办数据到门户
        foreach($data as $key=>$val){
            $neqdata = [
                    "syscode"=>$val["syscode"],
                    "flowid"=>$val["flowid"],
                    "requestname"=>$val["requestname"],
                    "workflowname"=>$val["workflowname"],
                    "nodename"=>$val["nodename"],
                    "receiver"=>$val["receiver"],
                    "receivets"=>$val["receivets"]
            ];
            $url = 'http://10.108.0.182:18081/rest/ofs/ProcessDoneRequestByJson';
            
            $res =  json_encode($neqdata,JSON_UNESCAPED_UNICODE);
            $method = 'POST';
            $header = [
                    'Content-Type:application/json',
                    'accept:*/*',
                    'connection:Keep-Alive'
                ];
            //dump($res);die;
            $dsdf = $this->http_curl($url,$method, $res, $header, $timeout = 10);
            if($dsdf['operResult'] == '1'){
                Db::name("processing_done")->where("flowid",$val["flowid"])->update(["status"=>2]);
              
           }else{
                Db::name("processing_done")->where("flowid",$val["flowid"])->update(["status"=>3]);
           }
        }
        return 1;
    }


    
    //获取个人的已办列表  
    public function message_handled($currentOpenUserId){
        if(empty($currentOpenUserId)){
            $result = [
                "code"=>-1,
                "msg"=>"currentOpenUserId不能为空",
                "data"=>""
            ];
            return json($result);
        }
        $gl_message_agent = $this->gl_message_handled($currentOpenUserId);
       
        if(empty($gl_message_agent)){
            $result = [
                "code"=>-1,
                "msg"=>"数据不存在",
                "data"=>""
            ];
            return json($result);
        }
        $result = $this->chuli_data($gl_message_agent);
        return $result;
    }

     //处理crm已办数据
     public function chuli_data($data){
        if(empty($data)){
            $result = [
                "code"=>-1,
                "msg"=>"数据不能为空",
                "data"=>""
            ];
            return json($result);
        }
        $list = [];
        foreach($data as $k=>$v){
            $time = time()*1000;
             //452审批流待办     457业务流待办
             if($v["bizType"] == "452"){
                $newData = [
                    "syscode"=>"XBCRM",//异构系统标识
                    "bizType"=>$v["bizType"],//待办类型
                    "flowid"=>$v["todoId"],//流程实例id
                    "requestname"=>$v["todoData"]["elements"][3]["value"],//标题
                    "workflowname"=>$v["todoData"]["elements"][1]["value"],//流程类型名称
                    "nodename"=>"CRM审批",//步骤名称（节点名称）
                    "receiver"=>implode(",",$v["employeeIds"]),//接收人
                    "receivets"=>"$time",//毫秒级时间戳
                ];
            }else{
                $newData = [
                    "syscode"=>"XBCRM",//异构系统标识
                    "bizType"=>$v["bizType"],//待办类型
                    "flowid"=>$v["todoId"],//流程实例id
                    "requestname"=>$v["title"],//标题
                    "workflowname"=>$v["todoData"]["elements"][0]["value"],//流程类型名称
                    "nodename"=>"CRM审批",//步骤名称（节点名称）
                    "receiver"=>implode(",",$v["employeeIds"]),//接收人
                    "receivets"=>"$time",//毫秒级时间戳
                ];
            }
          //接收人
          if($newData['receiver']){
            $newData["receiver"] = $this->flag_user_id($newData["receiver"]);
          }else{
            $newData["receiver"] = "";
          }
          array_push($list,$newData);
        }
        return $list;
       
    }

     //获取个人的待办列表
     public function message_todo($currentOpenUserId){
      
        if(empty($currentOpenUserId)){
            $result = [
                "code"=>-1,
                "msg"=>"currentOpenUserId不能为空",
                "data"=>""
            ];
            return json($result);
        }
        $gl_message_agent = $this->gl_message_todo($currentOpenUserId);
      
        //处理crm待办数据
        $resgh = $this->process_tododata($gl_message_agent,$currentOpenUserId);
        // dump($resgh);die;
        return $resgh;
      
    }
      //根据手机号获取crm用户id
      public function getByMobile($owner_id){
        $qwe = $this->corpAccessToken();
        $url ='https://open.fxiaoke.com/cgi/user/getByMobile';  // 根据手机号查询员工
        $corpAccessToken = $qwe['corpAccessToken'];   
        $corpId = $qwe['corpId'];
        //$mobile = "18394181267";
        $phone = explode(",",$owner_id);
        $sdf = [];
        foreach ($phone as $mobile){
            $res =  json_encode(compact('corpAccessToken', 'corpId', 'mobile'),JSON_UNESCAPED_UNICODE);
        
            $method = 'POST';
            $header = [
                            'Content-Type:application/json'
                        ];
            $dsdf = $this->http_curl($url,$method, $res, $header);
            if(!empty($dsdf) && isset($dsdf) && $dsdf['errorCode'] == '0' && $dsdf['errorMessage'] == 'success' && !empty($dsdf['empList']) )
            {
            $sdf[] = $dsdf['empList'][0]["openUserId"];
            }
        }
        return $sdf;
    }

    //处理crm待办数据
    public function process_tododata($data,$currentOpenUserId){
       //dump($data);die;
        if(empty($data)){
            $result = [
                "code"=>-1,
                "msg"=>"数据不能为空",
                "data"=>""
            ];
            return json($result);
        }
        $list = [];
        foreach($data as $k=>$v){
            $pcurl = 'https://www.fxiaoke.com/XV/UI/detail?apiname='.$v["objectApiName"].'&id='.$v["objectId"];
            $time = time()*1000;
            //452审批流待办     457业务流待办
            if($v["bizType"] == "452"){
                $newData = [
                    "syscode"=>"XBCRM",//异构系统标识
                    "bizType"=>$v["bizType"],//待办类型
                    "flowid"=>$v["todoId"],//流程实例id
                    "requestname"=>$v["todoData"]["elements"][3]["value"],//标题
                    "workflowname"=>$v["todoData"]["elements"][1]["value"],//流程类型名称
                    "nodename"=>"CRM审批",//步骤名称（节点名称）
                    "pcurl"=>$pcurl,//PC地址
                    "appurl"=>"www.baidu.com",//APP地址
                    "isremark"=>"0",//流程处理状态
                    "viewtype"=>$v["unRead"],//流程查看状态
                    "creator"=>$v["todoData"]["elements"][1]["value"],//创建人
                    "createdatetime"=>date('Y-m-d h:i:s', floor($v['createTimeStamp'] / 1000)), //创建日期时间
                    "receiver"=>implode(",",$v["employeeIds"]),//接收人
                    "receivedatetime"=>$v["todoData"]["elements"][2]["value"],//接收日期时间
                    "receivets"=>"$time",//毫秒级时间戳
                ];
                //创建人
                if(!empty($newData['creator'])){
                    $newData["creator"] = $this->flag_created_by($newData['creator']);
                }else{
                    $newData["creator"] = "";
                }
            }else{
                //查询业务流待办的创建人
               $yewycreator = $this->yewycreator("BpmInstance",$v["urlParameters"]["workflowInstanceId"],$currentOpenUserId);
               if(empty($yewycreator)){
                    $field_v86j2__c = "";
               }else{
                    $relevant_team__r = $yewycreator;
                    //根据创建人姓名查询EAS用户编码
                    $field_v86j2__c = $this->flag_created_by($relevant_team__r);
               }
                $newData = [
                    "syscode"=>"XBCRM",//异构系统标识
                    "bizType"=>$v["bizType"],//待办类型
                    "flowid"=>$v["todoId"],//流程实例id
                    "requestname"=>$v["title"],//标题
                    "workflowname"=>$v["todoData"]["elements"][0]["value"],//流程类型名称
                    "nodename"=>"CRM审批",//步骤名称（节点名称）
                    "pcurl"=>$pcurl,//PC地址
                    "appurl"=>"www.baidu.com",//APP地址
                    "isremark"=>"0",//流程处理状态
                    "viewtype"=>$v["unRead"],//流程查看状态
                    "creator"=>$field_v86j2__c,//创建人
                    "createdatetime"=>date('Y-m-d h:i:s', floor($v['createTimeStamp'] / 1000)), //创建日期时间
                    "receiver"=>implode(",",$v["employeeIds"]),//接收人
                    "receivedatetime"=>$v["todoData"]["elements"][1]["value"],//接收日期时间
                    "receivets"=>"$time",//毫秒级时间戳
                ];
            }

          if($newData['viewtype']){
            $newData["viewtype"] = "1";
          }else{
            $newData["viewtype"] = "0";
          }
          $newData["receivedatetime"] = $newData["receivedatetime"].':00';
          //接收人
          if($newData['receiver']){
            $newData["receiver"] = $this->flag_user_id($newData["receiver"]);
          }else{
            $newData["receiver"] = "";
          }
          array_push($list,$newData);
        }
       // dump($list);die;
        return $list;
       
    }

    //查询业务流待办创建人
    public function yewycreator($objectApiName,$objectId,$tel){
        $qwe = $this->corpAccessToken();
        $url = 'https://open.fxiaoke.com/cgi/crm/v2/data/get';
        $corpAccessToken = $qwe['corpAccessToken'];   
        $corpId = $qwe['corpId'];
        $currentOpenUserId = "FSUID_6ACD1FE372B9214FB126D40DE34C8BF3";//FSUID_6ACD1FE372B9214FB126D40DE34C8BF3
        $data = ['objectDataId'=>$objectId,'dataObjectApiName'=>$objectApiName];
        $res =  json_encode(compact('corpAccessToken', 'corpId', 'currentOpenUserId', 'data'),JSON_UNESCAPED_UNICODE);
        $method = 'POST';
        $header = [
                       'Content-Type:application/json'
                   ];
        
        $dsdf = $this->http_curl($url,$method, $res, $header, $timeout = 10);
        if($dsdf['errorMessage'] == 'OK' && $dsdf['errorCode'] == 0){
            if(!empty($dsdf["data"])){
                return $dsdf["data"]["owner__r"]["name"];
            }else{
                return "";
            }
            
        }else{
            return "";
        }
    }

     //查询已办消息
     public function gl_message_handled($tel){
        $qwe = $this->corpAccessToken();
        $url = 'https://open.fxiaoke.com/cgi/crm/v2/special/getTodoDealViewList';
        $corpAccessToken = $qwe['corpAccessToken'];   
        $corpId = $qwe['corpId'];
        $currentOpenUserId = $tel;//FSUID_B9743F457C3ABD3C3FA9473741D905DE
        $data = ['app'=>'ALL'];
        $res =  json_encode(compact('corpAccessToken', 'corpId', 'currentOpenUserId', 'data'),JSON_UNESCAPED_UNICODE);
        $method = 'POST';
        $header = [
                       'Content-Type:application/json'
                   ];
        $dsdf = $this->http_curl($url,$method, $res, $header, $timeout = 10);
     
        if($dsdf['errorMessage'] == 'OK' && $dsdf['errorCode'] == 0){
            if(!empty($dsdf["data"]["todoDealViewList"])){
                return $dsdf["data"]["todoDealViewList"];
            }else{
                return "";
            }
            
        }else{
            return "";
        }
    }

    //查询待办消息
    public function gl_message_todo($curuserid){
        $qwe = $this->corpAccessToken();
        $url = 'https://open.fxiaoke.com/cgi/crm/v2/special/getTodoViewList';
        $corpAccessToken = $qwe['corpAccessToken'];   
        $corpId = $qwe['corpId'];
        $currentOpenUserId = $curuserid;//FSUID_B9743F457C3ABD3C3FA9473741D905DE
        $data = ['app'=>'ALL'];
        $res =  json_encode(compact('corpAccessToken', 'corpId', 'currentOpenUserId', 'data'),JSON_UNESCAPED_UNICODE);
        $method = 'POST';
        $header = [
                       'Content-Type:application/json'
                   ];
        $dsdf = $this->http_curl($url,$method, $res, $header, $timeout = 10);
        if($dsdf['errorMessage'] == 'OK' && $dsdf['errorCode'] == 0){
            if(!empty($dsdf["data"]["todoViewList"])){
                return $dsdf["data"]["todoViewList"];
            }else{
                return "";
            }
            
        }else{
            return "";
        }
    }

     //根据创建人查询员工EAS编码
     public function flag_created_by($full_name){
       // $name = "";//FSUID_C508A03A3F8C43C1155D5816CF702B34  -10000  18394181267 FSUID_347B3D825747C232B5D9327DC06A64D2
        $qwe = $this->corpAccessToken();
        $url ='https://open.fxiaoke.com/cgi/crm/v2/data/query';//'https://open.fxiaoke.com/cgi/crm/v2/data/query';  //根据条件查询人员对象的列表
        $corpAccessToken = $qwe['corpAccessToken'];   
        $corpId = $qwe['corpId'];
        $currentOpenUserId = 'FSUID_C508A03A3F8C43C1155D5816CF702B34';//field_v86j2__c  phone
        $data = [
            'dataObjectApiName'=>'PersonnelObj',
            'search_query_info'=>[ 
                'offset'=>0, 
                'limit'=>1, 
                'filters'=>[
                    [ 
                        'field_name'=>'full_name',
                        'field_values'=>[$full_name],
                        'operator'=>'EQ' 
                    ]
                ]
            ]
        ];
        $res =  json_encode(compact('corpAccessToken', 'corpId', 'currentOpenUserId', 'data'),JSON_UNESCAPED_UNICODE);
       
        $method = 'POST';
        $header = [
                       'Content-Type:application/json'
                   ];
        $dsdf = $this->http_curl($url,$method, $res, $header, $timeout = 10);
        if(!empty($dsdf) && isset($dsdf) && $dsdf['errorCode'] == '0' && $dsdf['errorDescription'] == 'success' && $dsdf['errorMessage'] == 'OK')
         {
             if(empty($dsdf["data"]["dataList"])){
                return "";
             }else{
                return $dsdf["data"]["dataList"][0]["field_v86j2__c"];
             }
            
         }else{
            return ""; 
         }
   }

    //根据user_id查询员工EAS编码
    public function flag_user_id($userid){
        //$userid = "FSUID_C508A03A3F8C43C1155D5816CF702B34";
        $qwe = $this->corpAccessToken();
        $url ='https://open.fxiaoke.com/cgi/crm/v2/data/query';  //根据条件查询人员对象的列表
        $corpAccessToken = $qwe['corpAccessToken'];   
        $corpId = $qwe['corpId'];
        $currentOpenUserId = 'FSUID_C508A03A3F8C43C1155D5816CF702B34';//field_v86j2__c  phone
        $data = [
            'dataObjectApiName'=>'PersonnelObj',
            'search_query_info'=>[ 
                'offset'=>0, 
                'limit'=>1, 
                'filters'=>[
                    [ 
                        'field_name'=>'user_id',
                        'field_values'=>[$userid],
                        'operator'=>'EQ' 
                    ]
                ]
            ]
        ];
        $res =  json_encode(compact('corpAccessToken', 'corpId', 'currentOpenUserId', 'data'),JSON_UNESCAPED_UNICODE);
       // dump($res);die;
        $method = 'POST';
        $header = [
                       'Content-Type:application/json'
                   ];
        $dsdf = $this->http_curl($url,$method, $res, $header, $timeout = 10);
        if(!empty($dsdf) && isset($dsdf) && $dsdf['errorCode'] == '0' && $dsdf['errorDescription'] == 'success' && $dsdf['errorMessage'] == 'OK')
         {
             if(empty($dsdf["data"]["dataList"])){
                return "";
             }else{
                return $dsdf["data"]["dataList"][0]["field_v86j2__c"];
             }
            
         }else{
            return ""; 
         }
   }


       
    //根据用户id查询员工是否存在
    public function flag_usereqw($userid){
        //$userid = "007133";
        $qwe = $this->corpAccessToken();
        $url ='https://open.fxiaoke.com/cgi/crm/v2/data/query';  //根据条件查询人员对象的列表
        $corpAccessToken = $qwe['corpAccessToken'];   
        $corpId = $qwe['corpId'];
        $currentOpenUserId = 'FSUID_C508A03A3F8C43C1155D5816CF702B34';//field_v86j2__c  phone
        $data = [
            'dataObjectApiName'=>'PersonnelObj',
            'search_query_info'=>[ 
                'offset'=>0, 
                'limit'=>1, 
                'filters'=>[
                    [ 
                        'field_name'=>'field_v86j2__c',
                        'field_values'=>[$userid],
                        'operator'=>'EQ' 
                    ]
                ]
            ]
        ];
        $res =  json_encode(compact('corpAccessToken', 'corpId', 'currentOpenUserId', 'data'),JSON_UNESCAPED_UNICODE);
       // dump($res);die;
        $method = 'POST';
        $header = [
                       'Content-Type:application/json'
                   ];
        $dsdf = $this->http_curl($url,$method, $res, $header, $timeout = 10);
       // dump($dsdf);die;
        if(!empty($dsdf) && isset($dsdf) && $dsdf['errorCode'] == '0' && $dsdf['errorDescription'] == 'success' && $dsdf['errorMessage'] == 'OK')
         {
             if(empty($dsdf["data"]["dataList"])){
                return "";
             }else{
                return $dsdf["data"]["dataList"][0]["user_id"];
             }
            
         }else{
            return ""; 
         }
   }

     /**
     * 获取token
     */
    public function corpAccessToken()
    {
        $method = 'POST';
        $appId = 'FSAID_131aba6';//FSAID_131aba6  FSAD_131b260
        $appSecret = '69a6c56e23234bc9b56992f1468d103a';//69a6c56e23234bc9b56992f1468d103a  bc3f3bd184c54895aca794db584f36fa
        $permanentCode = 'F7BE99269E4BFC33400A92D039A3E28F';//F7BE99269E4BFC33400A92D039A3E28F  C4E757336822DECDBBBB2C6117ABF449
        $url = 'https://open.fxiaoke.com/cgi/corpAccessToken/get/V2';
        $header = [
                         'Content-Type:application/json'
                   ];
        $res =  json_encode(compact('appId', 'appSecret', 'permanentCode'));
        $data = $this->http_curl($url,$method, $res, $header, $timeout = 10); 
        
        if(!empty($data) && isset($data) && $data['errorCode'] ==0 && $data['errorMessage'] == 'success' )
        {
            $data['addtime'] = time();
            if(Db::name('atoken')->where('id',1)->find())
            {
               Db::name('atoken')->where('id',1)->update($data);  
            }else{
               Db::name('atoken')->insert($data);  
            }
           return $data;
        }
        
    }

      /**
    * 发送 post 请求 
    * @access protected
    * @return string
    */
    protected function http_curl($url, $method = 'POST', $data = array(), $header, $timeout = 10)
   {
       $curl = curl_init($url);
       $method = strtoupper($method);
       //请求方式啥
       curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
       //post请求
       if ($method == 'POST') curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
       //超时时间
       curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
       //设置header头
       // if ($header !== false) curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
       curl_setopt($curl, CURLOPT_HTTPHEADER, $header); 
       
       curl_setopt($curl, CURLOPT_FAILONERROR, false);
       //返回抓取数据
       curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
       //输出header头信息
       curl_setopt($curl, CURLOPT_HEADER, true);
       //TRUE 时追踪句柄的请求字符串，从 PHP 5.1.3 开始可用。这个很关键，就是允许你查看请求header
       curl_setopt($curl, CURLINFO_HEADER_OUT, true);

       //https请求
       if (1 == strpos("$" . $url, "https://")) {
           curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
           curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
       }
       $curlError = curl_error($curl);
       list($content, $status) = [curl_exec($curl), curl_getinfo($curl), curl_close($curl)];
       $status = $status;
       $headerStr = trim(substr($content, 0, $status['header_size']));
       $content = trim(substr($content, $status['header_size']));
        
        $cont = json_decode($content,true);
        
       //  $cont['headers'] =$headerStr;   //返回的头部信息去掉
        return $cont;

   }



}
